package jkCore.album;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.KeyEvent;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;

import org.cocos2dx.javascript.AppActivity;
import org.cocos2dx.javascript.service.SDKClass;

import java.io.File;
import java.util.ArrayList;
import java.util.UUID;

import jkCore.utils.Utils;
import me.minetsh.imaging.IMGEditActivity;
import me.minetsh.imaging.IMGGalleryActivity;
import me.minetsh.imaging.core.IMGMode;
import me.minetsh.imaging.gallery.model.IMGChooseMode;
import me.minetsh.imaging.gallery.model.IMGImageInfo;
import me.minetsh.imaging.gallery.model.IMGImageViewModel;

public class AlbumManager extends SDKClass {
    private static String TAG = "AlbumManager";
    private static AlbumManager instance;
    private static Context mContext;
    private Activity mActivity;

    public static final int ACTION_SELECT_IMAGE = 2;
    public static final int ACTION_TAKE_PHOTO = 3;
    public static final int ACTION_EDIT_IMAGE = 4;
    private Uri photoURI;
    private File mImageFile;
    private int mMaxNum;
    private static float mRatio;

    @Override
    public void init(Context context) {
        super.init(context);
        Log.d(TAG, "init ");

        instance = this;
        mContext = context;
        mActivity = (AppActivity) mContext;

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            builder.detectFileUriExposure();
        }
    }

    @Override
    public void setGLSurfaceView(GLSurfaceView view) {
        super.setGLSurfaceView(view);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult requestCode = " + requestCode + " resultCode = " + resultCode + " data = " + data);

        if (resultCode == Activity.RESULT_OK) {
            ArrayList<IMGImageInfo> imgs;
            switch (requestCode) {
                case ACTION_TAKE_PHOTO://拍照返回
                    if (photoURI != null) {//拍摄成功
                        IMGImageViewModel model = new IMGImageViewModel(photoURI);
                        imgs = new ArrayList<IMGImageInfo>();
                        imgs.add(new IMGImageInfo(model));
                        editImage(imgs.get(0));
                    }

                    break;

                case ACTION_SELECT_IMAGE:
                    imgs = IMGGalleryActivity.getImageInfos(data);
                    if (imgs != null && imgs.size() > 0) {
                        if (imgs.size() == 1) {
                            editImage(imgs.get(0));
                        } else {
                            onChooseImagesDone(imgs);
                        }
                    }

                    break;
                case ACTION_EDIT_IMAGE:
                    onImageEditDone();

                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.d(TAG, "onRequestPermissionsResult requestCode = " + requestCode + " permissions = " + permissions + " grantResults = " + grantResults);

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            switch (requestCode) {
                case ACTION_SELECT_IMAGE:
                case ACTION_EDIT_IMAGE:
                    chooseImages(mMaxNum);

                    break;

                case ACTION_TAKE_PHOTO:
                    doTakePhoto();

                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onNewIntent(Intent intent) {
    }

    @Override
    public void onRestart() {
    }

    @Override
    public void onStop() {
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    }

    @Override
    public void onStart() {
    }

    @Override
    public void onKeyDown(int keyCode, KeyEvent event) {

    }

// ============================================================================================
// =====================================   内部方法   ===========================================
// ============================================================================================

    /**
     * 检测相册权限
     *
     * @param actionCode
     */
    private void openAlbumWithPermissionsCheck(int actionCode) {
        Log.d(TAG, "openAlbumWithPermissionsCheck actionCode = " + actionCode);

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mActivity,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    actionCode);
        } else {
            chooseImages(mMaxNum);
        }
    }

    /**
     * 请求拍照权限
     */
    private void requestTakePhotoPermissions() {
        Log.d(TAG, "requestTakePhotoPermissions");

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mActivity,
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    ACTION_TAKE_PHOTO);
        } else {
            doTakePhoto();
        }
    }

    /**
     * 拍摄照片
     */
    private void doTakePhoto() {
        Log.d(TAG, "doTakePhoto");

        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        try {
            File photoFile = FileUtils.genEditFile();
            if (photoFile != null) {
                photoURI = Uri.fromFile(photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                mActivity.startActivityForResult(takePictureIntent, ACTION_TAKE_PHOTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 选择图片
     *
     * @param num
     */
    private void chooseImages(int num) {
        Log.d(TAG, "chooseImages num = " + num);

        if (num > 0) {
            mActivity.startActivityForResult(
                    IMGGalleryActivity.newIntent(mContext, new IMGChooseMode.Builder()
                            .setMaxChooseCount(num)
                            .build()),
                    ACTION_SELECT_IMAGE
            );
        }
    }

    /**
     * 多选完成回调
     *
     * @param images
     */
    private void onChooseImagesDone(ArrayList<IMGImageInfo> images) {
        ArrayList<String> paths = new ArrayList<String>();
        for (IMGImageInfo image : images) {
            Log.d(TAG, "onChooseImagesDone images = " + images);

            paths.add(image.getUri().getPath());
        }
        Utils.callCocos2dxJavascript("JKManager && JKManager.onChooseImgsDone && JKManager.onChooseImgsDone(%s)", paths);
    }

    /**
     * 编辑图片
     *
     * @param image
     */
    private void editImage(IMGImageInfo image) {
        Log.d(TAG, "editImages image = " + image);

        if (image != null) {
            mImageFile = new File(mContext.getFilesDir(), UUID.randomUUID().toString() + ".png");
            Bundle bundle = new Bundle();
            bundle.putSerializable(IMGEditActivity.EXTRA_EDIT_MODE, IMGMode.CLIP);
            mActivity.startActivityForResult(
                    new Intent(mContext, IMGEditActivity.class)
                            .putExtra(IMGEditActivity.EXTRA_IMAGE_URI, image.getUri())
                            .putExtra(IMGEditActivity.EXTRA_IMAGE_SAVE_PATH, mImageFile.getAbsolutePath())
                            .putExtra(IMGEditActivity.EXTRA_EDIT_MODE, bundle)
                            .putExtra(IMGEditActivity.EXTRA_EDIT_CLIP_RATIO, mRatio),
                    ACTION_EDIT_IMAGE
            );
        }
    }

    /**
     * 编辑完成回调
     */
    private void onImageEditDone() {
        String path = mImageFile.getPath();
        Log.d(TAG, "onImageEditDone path = " + path);

        ArrayList<String> paths = new ArrayList<String>();
        paths.add(path);
        Utils.callCocos2dxJavascript("JKManager && JKManager.onChooseImgsDone && JKManager.onChooseImgsDone(%s)", paths);
    }

// ============================================================================================
// =====================================   外部方法   ===========================================
// ============================================================================================

// ============================================================================================
// =====================================   静态方法   ===========================================
// ============================================================================================

    /**
     * 选择图片
     *
     * @param maxNumStr 最大选择数量
     * @param ratioStr  指定宽高比
     */
    public static void chooseImgs(String maxNumStr, String ratioStr) {
        int maxNum = Integer.parseInt(maxNumStr);
        float ratio = Integer.parseInt(ratioStr);
        Log.d(TAG, "chooseImgs maxNum = " + maxNum + " ratio = " + ratio);

        if (maxNum > 0) {
            mRatio = ratio;
            AlbumManager.instance.mMaxNum = maxNum;
            if (maxNum == 1) {
                AlbumManager.instance.openAlbumWithPermissionsCheck(ACTION_EDIT_IMAGE);
            } else {
                AlbumManager.instance.openAlbumWithPermissionsCheck(ACTION_SELECT_IMAGE);
            }
        }
    }

    public static void takePhoto(String ratioStr) {
        float ratio = Integer.parseInt(ratioStr);
        Log.d(TAG, "takePhoto ratio = " + ratio);

        mRatio = ratio;
        AlbumManager.instance.requestTakePhotoPermissions();
    }
}
